import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import { usePermissionStore } from '@/stores/permission'

// 定义路由类型
const routes: Array<RouteRecordRaw> = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
    meta: {
      title: '登录'
    }
  },
  {
    path: '/vr',
    name: 'Vr',
    component: () => import('@/views/vr.vue'),
    meta: {
      title: 'Vr'
    }
  },
  {
    path: '/',
    component: () => import('@/components/Layout/Layout.vue'),
    redirect: '/dashboard',
    children: [
      {
        path: '/dashboard',
        name: 'Dashboard',
        component: () => import('@/views/Dashboard.vue'),
        meta: { title: '仪表板', icon: 'el-icon-monitor',requiresAuth: true,affix: true,hidden: true },
      },
      {
        path: '/user',
        name: 'User',
        meta: { title: '系统管理', icon: '',hidden: true },
        children: [
          {
            path: 'system_user',
            name: 'SystemUser',
            component: () => import('@/views/user/UserList.vue'), 
            meta: { title: '超级管理员列表', icon: 'system_user', keepAlive: true, requiresAuth: true,hidden: true },
          },
          {
            path: 'system_tenant',
            name: 'SystemTenant',
            component: () => import('@/views/user/TenantList.vue'), 
            meta: { title: '租户管理', icon: 'system_tenant', keepAlive: true, requiresAuth: true,hidden: true },
          },
          {
            path: 'system_management',
            name: 'SystemManagement',
            component: () => import('@/views/user/SystemManagement.vue'), 
            meta: { title: '业务系统管理', icon: 'system_management', keepAlive: true, requiresAuth: true,hidden: true },
          },
          {
            path: 'menu',
            name: 'Menu',
            component: () => import('@/views/user/Menu.vue'),
            meta: { title: '菜单管理', icon: 'menu', keepAlive: true, requiresAuth: true,hidden: true }
          },
          {
            path: 'dict_type',
            name: 'DictType',
            component: () => import('@/views/user/DictManagement.vue'),
            meta: { title: '字典管理', icon: 'dict_type', keepAlive: true, requiresAuth: true,hidden: true }
          },
          {
            path: 'operation_log',
            name: 'OperationLog',
            component: () => import('@/views/user/OperationLog.vue'),
            meta: { title: '操作日志', icon: 'operation_log', keepAlive: true, requiresAuth: true,hidden: true }
          },
          {
            path: '/settings',
            name: 'Settings',
            component: () => import('@/views/user/Settings.vue'),
            meta: {
              title: '个人中心',
              requiresAuth: true
            }
          },
        ]
      },
      {
        path: '/basic',
        name: 'Basic',
        meta: { title: '基础管理', icon: '',hidden: true },
        children: [
          {
            path: 'role',
            name: 'Role',
            component: () => import('@/views/basic/Role.vue'), 
            meta: { title: '角色管理', icon: 'role', keepAlive: true, requiresAuth: true,hidden: true },
          },
          {
            path: 'organization',
            name: 'Organization',
            component: () => import('@/views/basic/Organization.vue'), 
            meta: { title: '组织管理', icon: 'organization', keepAlive: true, requiresAuth: true,hidden: true },
          },
          {
            path: 'member',
            name: 'Member',
            component: () => import('@/views/basic/Member.vue'), 
            meta: { title: '成员管理', icon: 'member', keepAlive: true, requiresAuth: true,hidden: true },
          },
          {
            path: 'customer',
            name: 'Customer',
            component: () => import('@/views/basic/Customer.vue'), 
            meta: { title: '客户管理', icon: 'customer', keepAlive: true, requiresAuth: true,hidden: true },
          }
        ]
      },
    ]
  },
  {
    path: '/:pathMatch(.*)*', // 404 页面
    name: 'NotFound',
    component: () => import('@/views/NotFound.vue')
  },
  {
    path: '/redirect',
    component: () => import('@/components/Layout/Layout.vue'),
    meta: { title: '重定向' ,hidden: true},
    children: [
      {
        path: '/redirect/:path(.*)',
        component: () => import('@/views/Redirect.vue')
      }
    ]
  }
]

// 判断是否是生产环境并设置 basename
const isProd = import.meta.env.MODE === 'production'
const history = createWebHistory(isProd ? '/web/' : '/')

const router = createRouter({
  history,
  routes
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  // 设置页面标题
  if (to.meta.title) {
    document.title = to.meta.title as string
  }

  const menuStr = localStorage.getItem('menu');
  let menuData = null;
  if (menuStr) {
    try {
      menuData = JSON.parse(menuStr);
      menuData.push({name: 1, code: "/dashboard"});
    } catch (e) {
      console.error('解析menu失败', e);
    }
  }

  // 检查是否需要认证
  if (to.meta.requiresAuth) {
    const isAuthenticated = localStorage.getItem('token')
    if (!isAuthenticated){
      console.log('未登录',to, from)
      next('/login')
      return
    }else{

      // 检查路由权限
      if (menuData && Array.isArray(menuData)) {
        // 查找是否有匹配的菜单项
        const hasPermission = menuData.some((item: { name: number; code: string }) => 
          item.code === to.path
        );
        console.log('hasPermission',hasPermission)
        if (!hasPermission) {
          next('/404');
          return;
        }
      }


      const permissionStore = usePermissionStore()
      // 如果权限数据为空，先获取权限
      if (permissionStore.permissions.length === 0) {
        try {
          const userIdStr = localStorage.getItem('userId');
          const userId = userIdStr ? parseInt(userIdStr, 10) : NaN;

          if (!isNaN(userId)) {
            await permissionStore.fetchPermissions(userId);
            next();
          } else {
            console.error('无效的用户ID');
            next('/login');
          }
        } catch (error) {
          console.error('权限加载失败:', error)
          // 可以根据情况跳转到登录页或错误页
          next('/login')
        }
      } else {
        next()
      }
    }
  } else {
    next()
  }
})



export default router